import { User } from 'src/common/storage'
import { Action as ActionType } from 'src/types/action'
import { Dispatch } from 'redux'
import { createRandomString } from 'src/common/utils'
import * as actions from './actionTypes'

// 设置 token
export const setTokenAction = (token: string): ActionType => ({
    type: actions.SET_TOKEN,
    data: token
})

// 设置用户信息
export const setUserInfoAction = (info: any): ActionType => ({
    type: actions.SET_USER_INFO,
    data: info
})

// 删除 token
export const removeTokenAction = ():ActionType => ({
    type: actions.REMOVE_TOKEN,
    data: ''
})

// 删除用户信息
export const removeUserInfoAction = ():ActionType => ({
    type: actions.REMOVE_USER_INFO,
    data: ''
})

// 获取用户信息
export const getUserInfoAction = () => async (dispatch: Dispatch) => {
    const getUserInfo = () => Promise.resolve({ status: 200, message: '', data: { name: 'hello' } })
    // const result = await UserModel.getUserInfo()
    const result = await getUserInfo()
    if (result.status === 200) {
        dispatch(setUserInfoAction(result.data))
        return result.data
    }
    return
}

// 重置用户信息
export const resetUserInfoAction = () => (dispatch: Dispatch) => {
    User.removeToken()
    dispatch(removeTokenAction())
    dispatch(removeUserInfoAction())
    window.location.href = '/'
}

// 登录
export const loginAction = (params: any) => async (dispatch: Dispatch) => {
    // 为了方便做演示，实际并不会这样
    const login = async (params: any) => new Promise((resolve, reject) => {
        const { username, password } = params
        console.log(username, password)
        if (username === 'admin' && password === 'admin') {
            return resolve({
                status: 200,
                message: 'ok',
                data: createRandomString()
            })
        }
        return resolve({
            status: 204,
            message: '登录失败',
            data: null
        })
    })
    const result: any = await login(params)

    if (result.status === 200) {
        const { token } = result.data
        // 持久化 token
        User.setToken(token)
        // 保存 token
        dispatch(setTokenAction(token))
        // 获取用户信息
        // await getUserInfoAction()
    }
    return result
}
